extends Node2D

enum CHARACTER_TYPE {PLAYER, ENEMY}

@export var curtain: ColorRect

func _ready():
	# 初始化Chessboard
	Chessboard._init()
	var player_scene = preload ("res://Piece/Character/player/player.tscn")
	var enemy_scene = preload ("res://Piece/Character/enemy/enemy.tscn")

	# 初始化角色1
	init_character(player_scene, [2, 2], CHARACTER_TYPE.PLAYER)

	# 初始化角色2
	init_character(player_scene, [1, 2], CHARACTER_TYPE.PLAYER)

	# 初始化敌人1
	init_character(enemy_scene, [4, 5], CHARACTER_TYPE.ENEMY)

	# 初始化敌人2
	init_character(enemy_scene, [4, 4], CHARACTER_TYPE.ENEMY)

	# 第一回合开始
	start_player_turn()

	# 追加一个遮罩层，防止在加载完成前，触发on mouse enter导致报错
	curtain.queue_free()

# 初始化角色
func init_character(scene, coord, type):
	# scene实例化
	var new_character = scene.instantiate()
	# 添加到scene中
	add_child(new_character)
	# 依据类型追加到对应的Chessboard list中
	if type == CHARACTER_TYPE.PLAYER:
		Chessboard.player_list.append(new_character)
	elif type == CHARACTER_TYPE.ENEMY:
		Chessboard.enemy_list.append(new_character)
		new_character.finish_action.connect(next_enemy_action)
	# Chessboard.move_array(new_character,[],coord)
	# 延迟调用move方法，防止GridContainer中的Grids位置还没有设定好
	new_character.call_deferred("move", coord)

	# 返回对象，主要是为了能直接调用其中的方法
	return new_character

# 点击结束回合后，调用这个方法
func end_player_turn():
	print("End - Turn")
	Chessboard.board_state = Chessboard.STATE.BLOCK
	# TODO 不要remove focus，而是block
	# Chessboard.focus_player.remove_focus()
	# TODO 进入地方回合，执行敌人的逻辑
	start_enemy_turn()

var enemy_index = 0
# 玩家角色结算完成后，开始敌方回合
func start_enemy_turn():
	# TODO 触发敌人回合开始时的判定效果
	# 各个敌人依次执行行动
	next_enemy_action()
	
func next_enemy_action():
	# FIXME 如果在enemy回合呢，有enemy死亡
	if len(Chessboard.enemy_list) > enemy_index:
		print("enemy index: ", enemy_index)
		enemy_index += 1
		Chessboard.enemy_list[enemy_index-1].start_action()
	else:
		enemy_index = 0
		end_enemy_turn()

# 敌方回合结束阶段
func end_enemy_turn():
	# TODO 触发敌人回合结束时的判定效果
	start_player_turn()

# 玩家回合开始
func start_player_turn():
	if Chessboard.focus_player == null:
		Chessboard.board_state = Chessboard.STATE.IDLE
		Chessboard.player_list[0].get_focus()
		Chessboard.player_list[1].remove_focus()
	else:
		Chessboard.board_state = Chessboard.STATE.PLAYER_MOVE
	# 执行所有玩家的回合开始方法
	for player in Chessboard.player_list:
		player.on_turn_start()
